<template>
  <div class="query-system">
    <!-- 头部 -->
    <div class="header">
      <div class="header-content">
        <h1 class="title">
          <span class="icon">🔍</span>
          跨表链接关键词查询系统
        </h1>
        <p class="subtitle">智能联合查询 · 多表关联 · 条件筛选</p>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 左侧面板 - 查询配置 -->
      <div class="left-panel">
        <!-- 表格选择卡片 -->
        <div class="card">
          <div class="card-header">
            <span class="card-icon">📊</span>
            <h3>选择查询表格</h3>
          </div>
          <div class="header-right">
            <button class="btn-refresh" @click="refreshTables" :disabled="isLoadingTables" title="刷新表列表">
              <span :class="{ 'rotating': isLoadingTables }">🔄</span>
            </button>
          </div>
        </div>
        <div class="card-body">
          <!-- 加载状态 -->
          <div v-if="isLoadingTables" class="loading-state">
            <div class="loading-spinner">⏳</div>
            <p>正在加载数据表...</p>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="loadError" class="error-state">
            <div class="error-icon">⚠️</div>
            <p>{{ loadError }}</p>
            <button class="btn-retry" @click="refreshTables">重试</button>
          </div>

          <!-- 表格列表 -->
          <div v-else class="table-selection">
            <div v-for="table in availableTables" :key="table.name"
              :class="['table-chip', { 'selected': selectedTables.includes(table.name) }]"
              @click="toggleTable(table.name)">
              <span class="chip-icon">{{ table.icon }}</span>
              <span class="chip-text">{{ table.name }}</span>
              <span class="chip-count">({{ table.fields.length }}字段)</span>
              <span v-if="selectedTables.includes(table.name)" class="chip-check">✓</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 关联字段配置 -->
      <div class="card" v-if="selectedTables.length >= 2">
        <div class="card-header">
          <span class="card-icon">🔗</span>
          <h3>配置表关联关系</h3>
        </div>
        <div class="card-body">
          <div class="relation-config">
            <div v-for="(relation, index) in tableRelations" :key="index" class="relation-item">
              <select v-model="relation.table1" class="select-field">
                <option value="">选择表1</option>
                <option v-for="table in selectedTables" :key="table" :value="table">{{ table }}</option>
              </select>
              <span class="relation-dot">●</span>
              <select v-model="relation.field1" class="select-field">
                <option value="">字段1</option>
                <option v-for="field in getTableFields(relation.table1)" :key="field" :value="field">
                  {{ field }}
                </option>
              </select>
              <span class="relation-arrow">⟷</span>
              <select v-model="relation.table2" class="select-field">
                <option value="">选择表2</option>
                <option v-for="table in selectedTables" :key="table" :value="table">{{ table }}</option>
              </select>
              <span class="relation-dot">●</span>
              <select v-model="relation.field2" class="select-field">
                <option value="">字段2</option>
                <option v-for="field in getTableFields(relation.table2)" :key="field" :value="field">
                  {{ field }}
                </option>
              </select>
              <button class="btn-icon-delete" @click="removeRelation(index)" title="删除关联">
                ✕
              </button>
            </div>
            <button class="btn-add" @click="addRelation">
              <span>+</span> 添加关联关系
            </button>
          </div>
        </div>
      </div>

      <!-- 查询条件配置 -->
      <div class="card">
        <div class="card-header">
          <span class="card-icon">⚙️</span>
          <h3>查询条件配置</h3>
        </div>
        <div class="card-body">
          <!-- 条件类型选择 -->
          <div class="condition-type">
            <label class="radio-label">
              <input type="radio" v-model="queryMode" value="simple" />
              <span>简单查询</span>
            </label>
            <label class="radio-label">
              <input type="radio" v-model="queryMode" value="advanced" />
              <span>高级查询</span>
            </label>
          </div>

          <!-- 简单查询模式 -->
          <div v-if="queryMode === 'simple'" class="simple-query">
            <div v-for="(condition, index) in simpleConditions" :key="index" class="condition-row">
              <select v-model="condition.table" class="select-field" @change="updateFieldOptions(index)">
                <option value="">选择表</option>
                <option v-for="table in selectedTables" :key="table" :value="table">{{ table }}</option>
              </select>

              <select v-model="condition.field" class="select-field">
                <option value="">选择字段</option>
                <option v-for="field in getTableFields(condition.table)" :key="field" :value="field">
                  {{ field }}
                </option>
              </select>

              <select v-model="condition.operator" class="select-field-small">
                <option value="=">=</option>
                <option value="!=">≠</option>
                <option value=">">></option>
                <option value="<">&lt;</option>
                <option value=">=">≥</option>
                <option value="<=">≤</option>
                <option value="LIKE">包含</option>
              </select>

              <input v-model="condition.value" type="text" class="input-field" placeholder="输入值" />

              <select v-if="index < simpleConditions.length - 1" v-model="condition.logic" class="select-field-small">
                <option value="AND">且</option>
                <option value="OR">或</option>
              </select>

              <button class="btn-icon-delete" @click="removeCondition(index)" title="删除条件">
                ✕
              </button>
            </div>
            <button class="btn-add" @click="addCondition">
              <span>+</span> 添加条件
            </button>
          </div>

          <!-- 高级查询模式 -->
          <div v-else class="advanced-query">
            <textarea v-model="advancedQuery" class="sql-textarea"
              placeholder="输入SQL条件语句，例如：&#10;Tab1.科室 = '内科' AND Tab2.诊断日期 >= '2024-01-01'&#10;或使用模糊查询：Tab2.病症 LIKE '%感%'"
              rows="6"></textarea>
            <div class="query-hints">
              <div class="hint-item">💡 支持 AND、OR 逻辑运算符</div>
              <div class="hint-item">💡 使用 LIKE '%关键字%' 进行模糊查询</div>
              <div class="hint-item">💡 表名.字段名格式指定条件</div>
            </div>
          </div>

          <!-- 条件模板 -->
          <div class="template-section">
            <div class="template-header">
              <span class="template-icon">📋</span>
              <span>条件模板</span>
            </div>
            <div class="template-actions">
              <button class="btn-template" @click="showSaveTemplate = !showSaveTemplate">
                💾 保存为模板
              </button>
              <button class="btn-template" @click="showLoadTemplate = !showLoadTemplate">
                📂 加载模板
              </button>
            </div>

            <!-- 保存模板弹窗 -->
            <div v-if="showSaveTemplate" class="template-modal">
              <input v-model="newTemplateName" type="text" class="input-field" placeholder="输入模板名称" />
              <div class="modal-buttons">
                <button class="btn-primary-small" @click="saveTemplate">保存</button>
                <button class="btn-secondary-small" @click="showSaveTemplate = false">取消</button>
              </div>
            </div>

            <!-- 加载模板列表 -->
            <div v-if="showLoadTemplate" class="template-list">
              <div v-for="(template, index) in savedTemplates" :key="index" class="template-item">
                <span class="template-name" @click="loadTemplate(template)">{{ template.name }}</span>
                <div class="template-item-actions">
                  <button class="btn-icon" @click="editTemplate(template)" title="编辑">✏️</button>
                  <button class="btn-icon" @click="deleteTemplate(index)" title="删除">🗑️</button>
                </div>
              </div>
              <div v-if="savedTemplates.length === 0" class="empty-state">
                暂无保存的模板
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 查询按钮组 -->
      <div class="action-buttons">
        <button class="btn-primary" @click="validateAndExecuteQuery">
          <span class="btn-icon">🔍</span>
          执行查询
        </button>
        <button class="btn-secondary" @click="resetQuery">
          <span class="btn-icon">🔄</span>
          重置
        </button>
      </div>
    </div>

    <!-- 右侧面板 - 查询结果 -->
    <div class="right-panel">
      <!-- 查询结果卡片 -->
      <div class="card results-card">
        <div class="card-header">
          <div class="header-left">
            <span class="card-icon">📈</span>
            <h3>查询结果</h3>
            <span v-if="queryResults.length > 0" class="result-count">
              共 {{ queryResults.length }} 条记录
            </span>
          </div>
          <div class="header-right" v-if="queryResults.length > 0">
            <button class="btn-export" @click="exportResults('excel')">
              📊 Excel
            </button>
            <button class="btn-export" @click="exportResults('csv')">
              📄 CSV
            </button>
            <button class="btn-export" @click="exportResults('pdf')">
              📕 PDF
            </button>
          </div>
        </div>

        <div class="card-body">
          <!-- 空状态 -->
          <div v-if="!hasQueried" class="empty-state-large">
            <div class="empty-icon">🔎</div>
            <p class="empty-title">等待查询</p>
            <p class="empty-desc">配置查询条件后点击"执行查询"按钮</p>
          </div>

          <!-- 无结果状态 -->
          <div v-else-if="queryResults.length === 0" class="empty-state-large">
            <div class="empty-icon">📭</div>
            <p class="empty-title">未找到匹配记录</p>
            <p class="empty-desc">请尝试调整查询条件</p>
          </div>

          <!-- 结果表格 -->
          <div v-else class="results-container">
            <!-- 表格工具栏 -->
            <div class="table-toolbar">
              <div class="toolbar-left">
                <input v-model="searchKeyword" type="text" class="search-input" placeholder="🔍 在结果中搜索..." />
              </div>
              <div class="toolbar-right">
                <span class="page-info">
                  第 {{ currentPage }} / {{ totalPages }} 页
                </span>
                <button class="btn-page" @click="prevPage" :disabled="currentPage === 1">
                  ◀
                </button>
                <button class="btn-page" @click="nextPage" :disabled="currentPage === totalPages">
                  ▶
                </button>
              </div>
            </div>

            <!-- 数据表格 -->
            <div class="table-wrapper">
              <table class="results-table">
                <thead>
                  <tr>
                    <th v-for="column in tableColumns" :key="column" @click="sortBy(column)" class="sortable">
                      {{ column }}
                      <span class="sort-indicator" v-if="sortColumn === column">
                        {{ sortDirection === 'asc' ? '▲' : '▼' }}
                      </span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, index) in paginatedResults" :key="index">
                    <td v-for="column in tableColumns" :key="column">
                      {{ row[column] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 统计信息 -->
            <div class="statistics">
              <div class="stat-item">
                <span class="stat-label">总记录数：</span>
                <span class="stat-value">{{ queryResults.length }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">当前页：</span>
                <span class="stat-value">{{ paginatedResults.length }} 条</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">查询时间：</span>
                <span class="stat-value">{{ queryTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


    <!-- 消息提示 -->
    <transition name="toast">
      <div v-if="toast.show" :class="['toast', toast.type]">
        <span class="toast-icon">{{ toast.icon }}</span>
        <span class="toast-message">{{ toast.message }}</span>
      </div>
    </transition>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'QuerySystem',

  data() {
    return {
      // 可用表格列表（这里可以通过API动态获取）
      availableTables: [],
      // 添加加载状态
      isLoadingTables: false,
      loadError: null,
      // 选中的表格
      selectedTables: [],

      // 表关联关系
      tableRelations: [],

      // 查询模式
      queryMode: 'simple', // 'simple' 或 'advanced'

      // 简单查询条件
      simpleConditions: [
        { table: '', field: '', operator: '=', value: '', logic: 'AND' }
      ],

      // 高级查询SQL
      advancedQuery: '',
      //最后一次返回的sql
      lastSQL: '',

      // 条件模板
      savedTemplates: [],
      showSaveTemplate: false,
      showLoadTemplate: false,
      newTemplateName: '',

      // 查询结果
      queryResults: [],
      hasQueried: false,
      queryTime: '',

      // 表格分页和排序
      currentPage: 1,
      pageSize: 10,
      sortColumn: '',
      sortDirection: 'asc',
      searchKeyword: '',

      // 消息提示
      toast: {
        show: false,
        type: 'info', // 'success', 'error', 'warning', 'info'
        icon: '',
        message: ''
      }
    };
  },

  computed: {
    // 表格列
    tableColumns() {
      if (this.queryResults.length === 0) return [];
      return Object.keys(this.queryResults[0]);
    },

    // 过滤后的结果
    filteredResults() {
      if (!this.searchKeyword) return this.queryResults;

      const keyword = this.searchKeyword.toLowerCase();
      return this.queryResults.filter(row => {
        return Object.values(row).some(value =>
          String(value).toLowerCase().includes(keyword)
        );
      });
    },

    // 排序后的结果
    sortedResults() {
      if (!this.sortColumn) return this.filteredResults;

      return [...this.filteredResults].sort((a, b) => {
        const aVal = a[this.sortColumn];
        const bVal = b[this.sortColumn];

        if (aVal === bVal) return 0;

        const result = aVal > bVal ? 1 : -1;
        return this.sortDirection === 'asc' ? result : -result;
      });
    },

    // 分页后的结果
    paginatedResults() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.sortedResults.slice(start, end);
    },

    // 总页数
    totalPages() {
      return Math.ceil(this.sortedResults.length / this.pageSize);
    }
  },

  methods: {
    // 获取表信息
    async fetchAvailableTables() {
      this.isLoadingTables = true;
      this.loadError = null;

      // 先测试后端连接
      console.log('🔍 开始获取表信息...');

      try {
        // 方法1：先测试简单接口
        console.log('步骤1: 测试后端连接...');
        const testResponse = await axios.get('http://localhost:5000/api/test', {
          timeout: 5000 // 5秒超时
        });
        console.log('✅ 后端连接成功:', testResponse.data);

        // 方法2：获取表信息
        console.log('步骤2: 获取表信息...');
        const response = await axios.get('http://localhost:5000/api/tables', {
          timeout: 10000 // 10秒超时
        });
        console.log('✅ 收到响应:', response.data);

        if (response.data.success) {
          this.availableTables = response.data.tables;
          this.showToast('success', '✅', `成功加载 ${this.availableTables.length} 个数据表`);
          console.log('📊 加载的表:', this.availableTables);
        } else {
          throw new Error(response.data.message || '获取表信息失败');
        }

      } catch (error) {
        console.error('❌ 错误详情:', error);

        // 详细的错误信息
        let errorMessage = '';

        if (error.code === 'ERR_NETWORK') {
          errorMessage = '无法连接到后端服务，请确认：\n1. 后端服务是否启动\n2. 地址是否正确：http://localhost:5000';
        } else if (error.code === 'ECONNREFUSED') {
          errorMessage = '后端服务未启动，请运行: node server.js';
        } else if (error.response) {
          // 服务器返回了错误
          errorMessage = `服务器错误: ${error.response.data?.message || error.message}`;
        } else if (error.request) {
          // 请求发出但没有收到响应
          errorMessage = '请求超时或无响应';
        } else {
          errorMessage = error.message;
        }

        this.loadError = errorMessage;
        this.showToast('error', '❌', errorMessage);

        // 使用示例数据
        console.log('⚠️ 使用示例数据');
        this.availableTables = [
          {
            name: '患者信息表',
            icon: '👤',
            fields: ['住院号', '姓名', '性别', '年龄', '联系方式']
          },
          {
            name: '诊疗记录表',
            icon: '📋',
            fields: ['患者号', '科室', '主治医生', '诊断日期', '诊断结果']
          }
        ];

      } finally {
        this.isLoadingTables = false;
      }
    },
    // // 新增：从后端获取表信息
    // async fetchAvailableTables() {
    //   this.isLoadingTables = true;
    //   this.loadError = null;

    //   try {
    //     // 调用后端API
    //     const response = await axios.get('http://localhost:8081/api/tables');

    //     if (response.data.success) {
    //       this.availableTables = response.data.tables;
    //       this.showToast('success', '✅', `成功加载 ${this.availableTables.length} 个数据表`);
    //     } else {
    //       throw new Error(response.data.message || '获取表信息失败');
    //     }

    //   } catch (error) {
    //     console.error('获取表信息失败:', error);
    //     this.loadError = error.message;
    //     this.showToast('error', '❌', '无法连接到数据库: ' + error.message);

    //     // 失败时使用默认示例数据
    //     this.availableTables = [
    //       { name: '患者信息表', icon: '👤', fields: ['住院号', '姓名', '性别', '年龄'] },
    //       { name: '诊疗记录表', icon: '📋', fields: ['患者号', '科室', '诊断日期'] }
    //     ];
    //   } finally {
    //     this.isLoadingTables = false;
    //   }
    // },

    // 新增：刷新表列表
    async refreshTables() {
      this.selectedTables = [];
      this.tableRelations = [];
      this.queryResults = [];
      await this.fetchAvailableTables();
    },
    // 切换表格选择
    toggleTable(tableName) {
      const index = this.selectedTables.indexOf(tableName);
      if (index > -1) {
        this.selectedTables.splice(index, 1);
        // 移除相关的关联关系
        this.tableRelations = this.tableRelations.filter(
          rel => rel.table1 !== tableName && rel.table2 !== tableName
        );
      } else {
        this.selectedTables.push(tableName);
        // 如果是第二张表，自动添加一个关联关系
        if (this.selectedTables.length === 2) {
          this.addRelation();
        }
      }
    },

    // 获取表的字段
    getTableFields(tableName) {
      const table = this.availableTables.find(t => t.name === tableName);
      return table ? table.fields : [];
    },

    // 添加关联关系
    addRelation() {
      this.tableRelations.push({
        table1: '',
        field1: '',
        table2: '',
        field2: ''
      });
    },

    // 移除关联关系
    removeRelation(index) {
      this.tableRelations.splice(index, 1);
    },

    // 添加查询条件
    addCondition() {
      this.simpleConditions.push({
        table: '',
        field: '',
        operator: '=',
        value: '',
        logic: 'AND'
      });
    },

    // 移除查询条件
    removeCondition(index) {
      if (this.simpleConditions.length > 1) {
        this.simpleConditions.splice(index, 1);
      }
    },

    // 更新字段选项
    updateFieldOptions(index) {
      this.simpleConditions[index].field = '';
    },

    // 验证并执行查询
    validateAndExecuteQuery() {
      // 验证表格选择
      if (this.selectedTables.length === 0) {
        this.showToast('error', '❌', '请至少选择一张表');
        return;
      }

      // 验证关联关系
      if (this.selectedTables.length >= 2 && this.tableRelations.length === 0) {
        this.showToast('warning', '⚠️', '多表查询需要配置关联关系');
        return;
      }

      // 验证关联关系完整性
      for (const relation of this.tableRelations) {
        if (!relation.table1 || !relation.field1 || !relation.table2 || !relation.field2) {
          this.showToast('error', '❌', '请完整配置所有关联关系');
          return;
        }
      }

      // 验证查询条件
      if (this.queryMode === 'simple') {
        for (const condition of this.simpleConditions) {
          if (!condition.table || !condition.field || !condition.value) {
            this.showToast('error', '❌', '请完整填写所有查询条件');
            return;
          }
        }
      } else {
        if (!this.advancedQuery.trim()) {
          this.showToast('error', '❌', '请输入查询条件');
          return;
        }
      }

      // 执行查询
      this.executeQuery();
    },

    // 执行查询
    async executeQuery() {
      const startTime = Date.now();

      try {
        // 构建查询参数
        const params = {
          tables: this.selectedTables,
          relations: this.tableRelations,
          mode: this.queryMode,
          conditions: this.queryMode === 'simple' ? this.simpleConditions : null,
          query: this.queryMode === 'advanced' ? this.advancedQuery : null
        };

        // 发送API请求
        const response = await axios.post('http://localhost:5000/api/query', params);

        // 更新结果
        this.queryResults = response.data.results || [];
        this.hasQueried = true;

        const endTime = Date.now();
        this.queryTime = `${endTime - startTime}ms`;
        this.lastSQL = (response.data && response.data.sql) ? String(response.data.sql) : '';
        // 重置分页
        this.currentPage = 1;
        this.sortColumn = '';
        this.searchKeyword = '';

        if (this.queryResults.length > 0) {
          this.showToast('success', '✅', `查询成功！找到 ${this.queryResults.length} 条记录`);
        } else {
          this.showToast('info', 'ℹ️', '查询完成，未找到匹配记录');
        }

      } catch (error) {
        console.error('查询失败:', error);
        this.showToast('error', '❌', '查询失败：' + (error.response?.data?.message || error.message));
      }
    },

    // 重置查询
    resetQuery() {
      this.selectedTables = [];
      this.tableRelations = [];
      this.simpleConditions = [{ table: '', field: '', operator: '=', value: '', logic: 'AND' }];
      this.advancedQuery = '';
      this.queryResults = [];
      this.hasQueried = false;
      this.currentPage = 1;
      this.searchKeyword = '';
      this.showToast('info', 'ℹ️', '已重置查询条件');
    },

    // 保存模板
    saveTemplate() {
      if (!this.newTemplateName.trim()) {
        this.showToast('warning', '⚠️', '请输入模板名称');
        return;
      }

      const template = {
        name: this.newTemplateName,
        mode: this.queryMode,
        tables: [...this.selectedTables],
        relations: JSON.parse(JSON.stringify(this.tableRelations))
      };

      if (this.queryMode === 'simple') {
        template.conditions = JSON.parse(JSON.stringify(this.simpleConditions));
      } else {
        template.query = this.advancedQuery;
      }

      this.savedTemplates.push(template);
      this.newTemplateName = '';
      this.showSaveTemplate = false;
      this.showToast('success', '✅', '模板保存成功');

      // 这里可以调用API保存到服务器
      // await axios.post('/api/templates', template);
    },

    // 加载模板
    loadTemplate(template) {
      this.selectedTables = [...template.tables] || [];
      this.tableRelations = JSON.parse(JSON.stringify(template.relations || []));
      this.queryMode = template.mode;

      if (template.mode === 'simple') {
        this.simpleConditions = JSON.parse(JSON.stringify(template.conditions || []));
      } else {
        this.advancedQuery = template.query || '';
      }

      this.showLoadTemplate = false;
      this.showToast('success', '✅', `已加载模板：${template.name}`);
    },

    // 编辑模板
    editTemplate(template) {
      this.loadTemplate(template);
      this.showToast('info', 'ℹ️', '模板已加载，可以进行编辑');
    },

    // 删除模板
    deleteTemplate(index) {
      if (confirm('确定要删除这个模板吗？')) {
        const templateName = this.savedTemplates[index].name;
        this.savedTemplates.splice(index, 1);
        this.showToast('success', '✅', `已删除模板：${templateName}`);

        // 这里可以调用API删除服务器上的模板
        // await axios.delete(`/api/templates/${id}`);
      }
    },

    // 排序
    sortBy(column) {
      if (this.sortColumn === column) {
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortColumn = column;
        this.sortDirection = 'asc';
      }
    },

    // 分页控制
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },


    // 导出结果（C 方案：后端重查 + 流式导出）
    async exportResults(format) {
      try {
        // 1) 选择用于导出的 SQL：
        //    - 优先使用最近一次后端返回的 SQL（推荐）
        //    - 如果没有，但当前是“高级模式”，直接用 advancedQuery
        let sqlForExport = this.lastSQL && this.lastSQL.trim()
          ? this.lastSQL.trim()
          : (this.queryMode === 'advanced' && this.advancedQuery && this.advancedQuery.trim()
            ? `SELECT * FROM ${this.selectedTables.join(', ')} WHERE ${this.advancedQuery.trim()}`
            : '');

        if (!sqlForExport) {
          this.showToast('error', '❌', '没有可导出的 SQL。请先执行查询。');
          return;
        }

        // 2) 发起导出：只传 sql + format，让后端重查并流式输出
        const response = await axios.post('http://localhost:5000/api/export', {
          sql: sqlForExport,
          params: [],             // 如需绑定参数可放这里
          format: format          // 'csv' | 'pdf'
        }, {
          responseType: 'blob',
          timeout: 100000, // 增加超时时间
        });

        // 处理文件下载
        const contentType = response.headers['content-type'];
        const contentDisposition = response.headers['content-disposition'];
        let filename = '导出文件';

        // 从 Content-Disposition 提取文件名
        if (contentDisposition) {
          const match = /filename\\*?=([^;]+)/i.exec(contentDisposition);
          if (match) {
            filename = decodeURIComponent(match[1].replace(/(^"|"$)/g, ''));
          }
        } else {
          // 没有 header 就用默认
          filename = format === 'pdf' ? 'export.pdf' :
            format === 'excel' || format === 'xlsx' ? 'export.xlsx' : 'export.csv';
        }

        // 触发浏览器下载
        const blob = new Blob([response.data], { type: contentType || 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        URL.revokeObjectURL(url);
        document.body.removeChild(a);

        this.showToast('success', '✅', '导出成功');

      } catch (error) {
        console.error('导出失败:', error);
        let msg = '导出失败';

        if (error.response && error.response.data) {
          try {
            const blob = error.response.data;
            const text = await blob.text();
            const json = JSON.parse(text);
            msg = json.message || msg;
          } catch {
            // ignore
          }
        } else if (error.message) {
          msg = error.message;
        }
        this.showToast('error', '❌', msg);
      }
    },

    // 显示消息提示
    showToast(type, icon, message) {
      this.toast = { show: true, type, icon, message };
      setTimeout(() => {
        this.toast.show = false;
      }, 3000);
    }
  },

  mounted() {
    // 组件挂载后可以从API获取可用表格
    // this.fetchAvailableTables();
  }
};
</script>

<style scoped>
/* 卡片头部布局 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 刷新按钮 */
.btn-refresh {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  padding: 6px 12px;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.3s ease;
  color: white;
}

.btn-refresh:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.btn-refresh:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 旋转动画 */
.rotating {
  display: inline-block;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.loading-spinner {
  font-size: 48px;
  margin-bottom: 15px;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 40px;
  color: #dc3545;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.btn-retry {
  margin-top: 15px;
  padding: 10px 20px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
}

.btn-retry:hover {
  background: #c82333;
  transform: translateY(-2px);
}

/* 字段数量标签 */
.chip-count {
  font-size: 12px;
  color: #6c757d;
  margin-left: auto;
}

.table-chip.selected .chip-count {
  color: rgba(255, 255, 255, 0.8);
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.query-system {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', sans-serif;
}

/* ===== 头部样式 ===== */
.header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  margin-bottom: 20px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.header-content {
  text-align: center;
}

.title {
  font-size: 32px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.icon {
  font-size: 36px;
}

.subtitle {
  color: #666;
  font-size: 16px;
  font-weight: 400;
}

/* ===== 主容器 ===== */
.main-container {
  display: grid;
  grid-template-columns: 420px, minmax(0, 1fr);
  gap: 20px;
  align-items: start;
}

/* 关键：让网格子项可缩，不要把列撑爆 */
.main-container>* {
  min-width: 0;
}

/* 把“切到单列”的阈值推迟，避免 1200px 就塌成一列 */
@media (max-width: 992px) {
  .main-container {
    grid-template-columns: 1fr;
  }
}

/* ===== 卡片样式 ===== */
.card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.12);
}

.card-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: space-between;
}

.header-left,
.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.card-icon {
  font-size: 24px;
}

.result-count {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 14px;
}

.card-body {
  padding: 20px;
}

/* ===== 表格选择 ===== */
.table-selection {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.table-chip {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
}

.table-chip:hover {
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.table-chip.selected {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
}

.chip-icon {
  font-size: 24px;
}

.chip-text {
  flex: 1;
  font-weight: 500;
}

.chip-check {
  font-size: 20px;
  font-weight: bold;
}

/* ===== 关联关系配置 ===== */
.relation-config {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.relation-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
}

.relation-dot {
  color: #667eea;
  font-size: 20px;
}

.relation-arrow {
  color: #764ba2;
  font-size: 20px;
  font-weight: bold;
}

/* ===== 表单元素 ===== */
.select-field,
.input-field {
  padding: 10px 14px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: white;
  flex: 1 1 180px;
}

.select-field:focus,
.input-field:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.select-field-small {
  padding: 10px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  width: 80px;
  background: white;
  flex: 0 0 auto;
  min-width: 84px;
}

/* ===== 查询条件 ===== */
.condition-type {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: 500;
}

.radio-label input[type="radio"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.condition-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
}

.sql-textarea {
  width: 100%;
  padding: 14px;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  font-size: 14px;
  font-family: 'Courier New', monospace;
  resize: vertical;
  transition: all 0.3s ease;
}

.sql-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.query-hints {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 12px;
  padding: 12px;
  background: #e3f2fd;
  border-radius: 8px;
}

.hint-item {
  font-size: 13px;
  color: #1976d2;
}

/* ===== 模板功能 ===== */
.template-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #e9ecef;
}

.template-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #495057;
}

.template-icon {
  font-size: 18px;
}

.template-actions {
  display: flex;
  gap: 10px;
}

.btn-template {
  flex: 1;
  padding: 10px 16px;
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-template:hover {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.template-modal {
  margin-top: 12px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.modal-buttons {
  display: flex;
  gap: 10px;
}

.template-list {
  margin-top: 12px;
  max-height: 200px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.template-item:hover {
  background: #e9ecef;
}

.template-name {
  cursor: pointer;
  font-weight: 500;
  flex: 1;
}

.template-item-actions {
  display: flex;
  gap: 8px;
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.btn-icon:hover {
  background: #dee2e6;
}

.btn-icon-delete {
  background: #fff5f5;
  color: #dc3545;
  border: none;
  cursor: pointer;
  font-size: 18px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-weight: bold;
  margin-left: auto;
  /* 推到当前行最右侧 */
  flex: 0 0 auto;
}

.btn-icon-delete:hover {
  background: #dc3545;
  color: white;
}

/* ===== 按钮样式 ===== */
.btn-add {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-add:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.btn-primary,
.btn-secondary {
  flex: 1;
  padding: 16px 24px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-secondary:hover {
  background: #667eea;
  color: white;
}

.btn-primary-small,
.btn-secondary-small {
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  flex: 1;
}

.btn-primary-small {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-secondary-small {
  background: #f8f9fa;
  color: #495057;
}

.btn-export {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-export:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

/* ===== 结果展示 ===== */
.results-card {
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.results-card .card-body {
  flex: 1;
  overflow: visible;
  display: flex;
  flex-direction: column;
}

.empty-state,
.empty-state-large {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.empty-state-large {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #495057;
}

.empty-desc {
  font-size: 14px;
  color: #6c757d;
}

.results-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e9ecef;
}

.search-input {
  padding: 10px 14px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  width: 300px;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  font-size: 14px;
  color: #6c757d;
}

.btn-page {
  padding: 8px 12px;
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-page:hover:not(:disabled) {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
  border-radius: 10px;
  border: 2px solid #e9ecef;
}

.results-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.results-table thead {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

.results-table th {
  padding: 14px;
  text-align: left;
  font-weight: 600;
  cursor: pointer;
  user-select: none;
  position: relative;
}

.results-table th.sortable:hover {
  background: rgba(255, 255, 255, 0.1);
}

.sort-indicator {
  margin-left: 8px;
  font-size: 12px;
}

.results-table tbody tr {
  border-bottom: 1px solid #e9ecef;
  transition: all 0.2s ease;
}

.results-table tbody tr:hover {
  background: #f8f9fa;
}

.results-table td {
  padding: 12px 14px;
  font-size: 14px;
  color: #495057;
}

.statistics {
  display: flex;
  gap: 30px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 2px solid #e9ecef;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  color: #6c757d;
  font-size: 14px;
}

.stat-value {
  color: #667eea;
  font-weight: 600;
  font-size: 16px;
}

/* ===== 消息提示 ===== */
.toast {
  position: fixed;
  top: 30px;
  right: 30px;
  padding: 16px 24px;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 500;
  z-index: 1000;
  min-width: 300px;
}

.toast.success {
  background: #d4edda;
  color: #155724;
  border: 2px solid #c3e6cb;
}

.toast.error {
  background: #f8d7da;
  color: #721c24;
  border: 2px solid #f5c6cb;
}

.toast.warning {
  background: #fff3cd;
  color: #856404;
  border: 2px solid #ffeeba;
}

.toast.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 2px solid #bee5eb;
}

.toast-icon {
  font-size: 20px;
}

.toast-message {
  flex: 1;
}

/* ===== 动画效果 ===== */
.toast-enter-active,
.toast-leave-active {
  transition: all 0.3s ease;
}

.toast-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.toast-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

/* ===== 响应式设计 ===== */
@media (max-width: 1200px) {
  .main-container {
    grid-template-columns: 1fr;
  }

  .results-card {
    height: auto;
  }
}

@media (max-width: 768px) {
  .query-system {
    padding: 10px;
  }

  .header {
    padding: 20px;
  }

  .title {
    font-size: 24px;
  }

  .table-selection {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    max-height: 260px;
    /* 关键：限制高度 */
    overflow: auto;
    /* 超出滚动，避免整体被拉高 */
  }

  /* 窄屏时单列更友好 */
  @media (max-width: 768px) {
    .table-selection {
      grid-template-columns: 1fr;
    }
  }

  .relation-item {
    flex-wrap: wrap;
  }

  .condition-row {
    flex-wrap: wrap;
  }

  .search-input {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
  }

  .toast {
    right: 10px;
    left: 10px;
    min-width: auto;
  }
}

/* ===== 滚动条样式 ===== */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #764ba2;
}
</style>